import network
from utime import sleep

class WLAN:
    @property
    def linked(self):
        return self.wlan.isconnected()

    def get_ip(self):
        return self.wlan.ifconfig()[0]

    def get_mac(self,byte=False):
        ''' 获取设备 mac 地址'''
        if not byte:
            import ubinascii
            return ubinascii.hexlify(self.wlan.config('mac'),':').decode()
        else:
            return self.wlan.config('mac')

class WIFI(WLAN):
    def __init__(self):
        self.wlan = network.WLAN(network.STA_IF)
        self.wlan.active(True)

    def get_wifi_list(self):
        try:
            return [x[0].decode() for x in self.wlan.scan() if x[0]]
        except:
            return

    def connect(self,ssid="flasoft",pawd="13695948637",timeout=10):
        try:
            self.wlan.connect(ssid,pawd)
            link_time = 0
            while not self.linked:
                link_time += 1
                if link_time < timeout:
                    print("reconnecting (%s)..."%(link_time))
                else:
                    return
                sleep(1)
            return True
        except:
            return

class AP(WLAN):
    def __init__(self,ssid="ESP-SERVER",pawd="13695948637"):
        self.wlan = network.WLAN(network.AP_IF)
        self.wlan.active(True)
        # 官网这个参数写的是ssid，会报错
        self.wlan.config(authmode=4,essid=ssid,password=pawd)